﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FHost1
{
    public partial class FormMyUploads : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.Cookies.AllKeys.Contains("fhostuser"))
            {
                Response.Redirect("Default.aspx?login=0");
            }

            int userId = Convert.ToInt32(Request.Cookies["fhostuser"].Value.Split('~')[0]);
            if (!IsPostBack)
            {
                int mainFolder = 0;
                if (Request.Cookies.AllKeys.Contains("cfolder"))
                {
                    mainFolder = Convert.ToInt32(Request.Cookies["cfolder"].Value);
                    Request.Cookies["cfolder"].Expires = DateTime.MinValue;
                }
                else
                {
                    using (FHostDataContext dataContext = new FHostDataContext())
                    {
                        mainFolder = dataContext.GetUserMainFolder(userId).Value;
                    }
                }

                GetFolderFiles(mainFolder);
                GetUserSpaceInfo();
            }
        }

        private void GetFolderFiles(int? folderId)
        {
            int userId = Convert.ToInt32(Request.Cookies["fhostuser"].Value.Split('~')[0]);
            using (FHostDataContext dataContext = new FHostDataContext())
            {
                var result = dataContext.GetUserFolderFiles(folderId, userId);

                gridFolderFiles.DataSource = result;
                gridFolderFiles.DataBind();
            }

            if (folderId.HasValue)
            {
                hfCurrentFolder.Value = folderId.Value.ToString();
            }
        }

        private void GetUserSpaceInfo()
        {
            int userId = Convert.ToInt32(Request.Cookies["fhostuser"].Value.Split('~')[0]);
            using (FHostDataContext dataContext = new FHostDataContext())
            {
                decimal? alloted = 0M;
                decimal? usedspace = 0M;
                dataContext.GetUserSpaceUsed(userId, ref alloted, ref usedspace);
                lblSpaceStatus.Text = string.Format("Space used: {0} /{1} MB Used", usedspace, alloted);
            }
        }

        protected void btnCreateFolder_Click(object sender, EventArgs e)
        {
            try
            {
                int userId = Convert.ToInt32(Request.Cookies["fhostuser"].Value.Split('~')[0]);
                using (FHostDataContext dataContext = new FHostDataContext())
                {
                    int? folderId = null;
                    if (!string.IsNullOrEmpty(hfCurrentFolder.Value))
                    {
                        folderId = Convert.ToInt32(hfCurrentFolder.Value);
                    }

                    if (!dataContext.CheckFolderExists(txtFolderName.Text.Trim(), folderId).Value)
                    {
                        Folder folder = new Folder()
                        {
                            UserID = userId,
                            ParentFolderID = folderId,
                            FolderName = txtFolderName.Text.Trim(),
                            CreatedDate = DateTime.Now
                        };

                        dataContext.Folders.InsertOnSubmit(folder);
                        dataContext.SubmitChanges();
                        GetFolderFiles(folderId);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(pnlUpdate, this.GetType(), "alert", "alert('Folder already exists')", true);
                    }
                }
            }
            catch
            {
            }
        }

        protected void btnFileDelete_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton imgBtn = sender as ImageButton;
            int uid = Convert.ToInt32(imgBtn.Attributes["UID"]);
            string utype = imgBtn.Attributes["UType"];
            using (FHostDataContext dataContext = new FHostDataContext())
            {
                if (utype == "FOLDER")
                {
                    dataContext.DeleteFolder(uid);
                }
                else if (utype == "FILE")
                {
                    dataContext.DeleteFile(uid);
                }
            }

            int? folderId = null;
            if (!string.IsNullOrEmpty(hfCurrentFolder.Value))
            {
                folderId = Convert.ToInt32(hfCurrentFolder.Value);
            }

            GetFolderFiles(folderId);
        }

        protected void btnUploadFile_Click(object sender, ImageClickEventArgs e)
        {
            //Session["cfolder"] = hfCurrentFolder.Value;
            Response.Cookies.Add(new HttpCookie("cfolder", hfCurrentFolder.Value));
            Response.Cookies["cfolder"].Expires = DateTime.Now.AddDays(1);
            Response.Redirect("UploadFile.aspx");
            //Response.Redirect(string.Format("UploadFile.aspx?folderid={0}", hfCurrentFolder.Value));
        }

        protected void lnkFolderFile_Click(object sender, EventArgs e)
        {
            LinkButton imgBtn = sender as LinkButton;
            int uid = Convert.ToInt32(imgBtn.Attributes["UID"]);
            string utype = imgBtn.Attributes["UType"];
            if (utype == "FOLDER")
            {
                GetFolderFiles(uid);
            }
        }

        protected void btnGoUp_Click(object sender, ImageClickEventArgs e)
        {
            int folderId = Convert.ToInt32(hfCurrentFolder.Value);
            using (FHostDataContext dataContext = new FHostDataContext())
            {
                int? parentFolderID = dataContext.GetParentFolder(folderId);
                if (parentFolderID.HasValue)
                {
                    GetFolderFiles(parentFolderID.Value);
                }
            }
        }

        protected void gridFolderFiles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                FHost1.GetUserFolderFilesResult rowDataItem = (FHost1.GetUserFolderFilesResult)e.Row.DataItem;
                if (rowDataItem.UType == "FILE")
                {
                    HyperLink hlLink = e.Row.FindControl("hlFileLink") as HyperLink;
                    hlLink.Visible = true;
                    hlLink.NavigateUrl = string.Format("~/DownloadHandler.ashx?id={0}", rowDataItem.ID);
                }
                else 
                {
                    (e.Row.FindControl("lnkFolderFile") as LinkButton).Visible = true;
                }
            }
        }
    }
}